<template>
	<div>
		<a-card :bordered="false" :title="props.tableName">
			<template #extra>
				<a
					v-if="dbColumnList.length > 0"
					@click="
						formRef.onOpen({
							dbsId: props.dbsId,
							tableName: props.tableName,
							tableRemark: props.tableRemark
						})
					"
				>
					<plus-outlined />
					新增
				</a>
			</template>
			<a-table
				v-if="dbColumnList.length > 0"
				:dataSource="dbColumnList"
				:columns="columns"
				:scroll="{ y: 600 }"
				:pagination="false"
				bordered
				size="middle"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'action'">
						<div>
							<a @click="formRef.onOpen({ ...record, dbsId: props.dbsId, tableName: props.tableName, tableRemark: props.tableRemark, isEdit: true })">
								修改
							</a>
							<a-divider type="vertical" />
							<a-popconfirm title="确定要删除字段吗？" placement="topRight" @confirm="delColumn(record)">
								<a-button type="link" danger size="small">删除</a-button>
							</a-popconfirm>
						</div>
					</template>
				</template>
			</a-table>
			<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
		</a-card>
		<Form ref="formRef" @successful="formSuccessful" />
	</div>
</template>
<script setup>
	import Form from './form.vue'
	import { Empty } from 'ant-design-vue'
	import dmApi from '@/views/plugin/dbs/api/dmApi'

	const props = defineProps({
		dbsId: {
			type: String,
			request: true,
			default: ''
		},
		tableName: {
			type: String,
			request: true,
			default: ''
		},
		tableRemark: {
			type: String,
			request: false,
			default: ''
		}
	})
	const columns = ref([
		{
			title: '字段名称',
			dataIndex: 'columnName',
			align: 'center'
		},
		{
			title: '字段注释',
			dataIndex: 'columnRemark',
			align: 'center'
		},
		{
			title: '字段类型',
			dataIndex: 'columnType',
			align: 'center'
		},
		{
			title: '字段长度',
			dataIndex: 'columnLength',
			width: 100,
			align: 'center'
		},
		{
			title: '操作',
			dataIndex: 'action',
			width: 120,
			align: 'center'
		}
	])
	// 数据库字段
	const dbColumnList = ref([])
	const formRef = ref()

	// 获取数据库字段
	const getDbColumnList = () => {
		const param = {
			dbsId: props.dbsId,
			tableName: props.tableName
		}
		dmApi.columns(param).then((data) => {
			dbColumnList.value = data
		})
	}

	const formSuccessful = () => {
		getDbColumnList()
	}

	const delColumn = (item) => {
		const param = {
			dbsId: props.dbsId,
			tableName: props.tableName,
			columnName: item.columnName
		}
		dmApi.deleteColumn(param).then(() => {
			getDbColumnList()
		})
	}

	// 抛出函数
	defineExpose({
		getDbColumnList
	})
</script>
